package com.koi.mqttdemo.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.koi.mqttdemo.MainActivity;
import com.koi.mqttdemo.Mqtt;
import com.koi.mqttdemo.inteface.IMqttGetMsgCallBack;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class MqttConnectionService extends Service {
    static Mqtt sMqtt = new Mqtt();
    public static Mqtt getMqttInstance() {
        return sMqtt;
    }
    public MqttConnectionService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        // 处理Mqtt链接

        sMqtt.initMqttClient(this,
                "ws://broker.mqttdashboard.com:8000",
                "testclientid",
                "usname",
                "uspawd",
                true,
                10,
                10);
        sMqtt.doConnect();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MqttAndroidClient client = sMqtt.getMqttAndroidClientInstance();
        try {
            client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
        client.unregisterResources();
        client.close();
    }

    private static   IMqttGetMsgCallBack sIMqttGetMsgCallBack;
    public static void setMqttReceiveCallBack(IMqttGetMsgCallBack IGetMessageCallBack) {
        sIMqttGetMsgCallBack = IGetMessageCallBack;
    }
    public static IMqttGetMsgCallBack getMqttReceiveCallBack() {
        return sIMqttGetMsgCallBack;
    }

}


